﻿#region Using Directives
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Web.UI;
using System.Web.UI.Design;

using Dienthoai.Entities;
using Dienthoai.Data;
using Dienthoai.Data.Bases;
#endregion

namespace Dienthoai.Web.Data
{
	/// <summary>
	/// Represents the DataRepository.NewsItemProvider object that provides
	/// data to data-bound controls in multi-tier Web application architectures.
	/// </summary>
	[Designer(typeof(NewsItemDataSourceDesigner))]
	public class NewsItemDataSource : ProviderDataSource<NewsItem, NewsItemKey>
	{
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the NewsItemDataSource class.
		/// </summary>
		public NewsItemDataSource() : base(DataRepository.NewsItemProvider)
		{
		}

		#endregion Constructors
		
		#region Properties
		
		/// <summary>
		/// Gets a reference to the NewsItemDataSourceView used by the NewsItemDataSource.
		/// </summary>
		protected NewsItemDataSourceView NewsItemView
		{
			get { return ( View as NewsItemDataSourceView ); }
		}
		
		/// <summary>
		/// Gets or sets the name of the method or function that
		/// the NewsItemDataSource control invokes to retrieve data.
		/// </summary>
		public NewsItemSelectMethod SelectMethod
		{
			get
			{
				NewsItemSelectMethod selectMethod = NewsItemSelectMethod.GetAll;
				Object method = ViewState["SelectMethod"];
				if ( method != null )
				{
					selectMethod = (NewsItemSelectMethod) method;
				}
				return selectMethod;
			}
			set { ViewState["SelectMethod"] = value; }
		}

		#endregion Properties
		
		#region Methods

		/// <summary>
		/// Creates a new instance of the NewsItemDataSourceView class that is to be
		/// used by the NewsItemDataSource.
		/// </summary>
		/// <returns>An instance of the NewsItemDataSourceView class.</returns>
		protected override BaseDataSourceView<NewsItem, NewsItemKey> GetNewDataSourceView()
		{
			return new NewsItemDataSourceView(this, DefaultViewName);
		}
		
		/// <summary>
        /// Creates a cache hashing key based on the startIndex, pageSize and the SelectMethod being used.
        /// </summary>
        /// <param name="startIndex">The current start row index.</param>
        /// <param name="pageSize">The current page size.</param>
        /// <returns>A string that can be used as a key for caching purposes.</returns>
		protected override string CacheHashKey(int startIndex, int pageSize)
        {
			return String.Format("{0}:{1}:{2}", SelectMethod, startIndex, pageSize);
        }
		
		#endregion Methods
	}
	
	/// <summary>
	/// Supports the NewsItemDataSource control and provides an interface for
	/// data-bound controls to perform data operations with business and data objects.
	/// </summary>
	public class NewsItemDataSourceView : ProviderDataSourceView<NewsItem, NewsItemKey>
	{
		#region Declarations

		#endregion Declarations
		
		#region Constructors

		/// <summary>
		/// Initializes a new instance of the NewsItemDataSourceView class.
		/// </summary>
		/// <param name="owner">A reference to the NewsItemDataSource which created this instance.</param>
		/// <param name="viewName">The name of the view.</param>
		public NewsItemDataSourceView(NewsItemDataSource owner, String viewName)
			: base(owner, viewName)
		{
		}
		
		#endregion Constructors
		
		#region Properties

		/// <summary>
		/// Gets a strongly-typed reference to the Owner property.
		/// </summary>
		internal NewsItemDataSource NewsItemOwner
		{
			get { return Owner as NewsItemDataSource; }
		}

		/// <summary>
		/// Gets or sets the name of the method or function that
		/// the DataSource control invokes to retrieve data.
		/// </summary>
		internal NewsItemSelectMethod SelectMethod
		{
			get { return NewsItemOwner.SelectMethod; }
			set { NewsItemOwner.SelectMethod = value; }
		}

		/// <summary>
		/// Gets a strongly typed reference to the Provider property.
		/// </summary>
		internal NewsItemProviderBase NewsItemProvider
		{
			get { return Provider as NewsItemProviderBase; }
		}

		#endregion Properties
		
		#region Methods
		 
		/// <summary>
		/// Gets a collection of Entity objects based on the value of the SelectMethod property.
		/// </summary>
		/// <param name="count">The total number of rows in the DataSource.</param>
	    /// <param name="values"></param>
		/// <returns>A collection of Entity objects.</returns>
		protected override IList<NewsItem> GetSelectData(IDictionary values, out int count)
		{
            if (values == null || values.Count == 0) values = CollectionsUtil.CreateCaseInsensitiveHashtable(GetParameterValues());
            
			Hashtable customOutput = CollectionsUtil.CreateCaseInsensitiveHashtable();
			IList<NewsItem> results = null;
			NewsItem item;
			count = 0;
			
			System.Int32 _itemId;

			switch ( SelectMethod )
			{
				case NewsItemSelectMethod.Get:
					NewsItemKey entityKey  = new NewsItemKey();
					entityKey.Load(values);
					item = NewsItemProvider.Get(GetTransactionManager(), entityKey);
					results = new TList<NewsItem>();
					if ( item != null ) results.Add(item);
					count = results.Count;
					break;
				case NewsItemSelectMethod.GetAll:
                    results = NewsItemProvider.GetAll(GetTransactionManager(), StartIndex, PageSize, out count);
                    break;
				case NewsItemSelectMethod.GetPaged:
					results = NewsItemProvider.GetPaged(GetTransactionManager(), WhereClause, OrderBy, PageIndex, PageSize, out count);
					break;
				case NewsItemSelectMethod.Find:
					if ( FilterParameters != null )
						results = NewsItemProvider.Find(GetTransactionManager(), FilterParameters, OrderBy, StartIndex, PageSize, out count);
					else
						results = NewsItemProvider.Find(GetTransactionManager(), WhereClause, StartIndex, PageSize, out count);
                    break;
				// PK
				case NewsItemSelectMethod.GetByItemId:
					_itemId = ( values["ItemId"] != null ) ? (System.Int32) EntityUtil.ChangeType(values["ItemId"], typeof(System.Int32)) : (int)0;
					item = NewsItemProvider.GetByItemId(GetTransactionManager(), _itemId);
					results = new TList<NewsItem>();
					if ( item != null ) results.Add(item);
					count = results.Count;
					break;
				// IX
				// FK
				// M:M
				// Custom
				default:
					break;
			}

			if ( results != null && count < 1 )
			{
				count = results.Count;

				if ( !String.IsNullOrEmpty(CustomMethodRecordCountParamName) )
				{
					object objCustomCount = EntityUtil.ChangeType(customOutput[CustomMethodRecordCountParamName], typeof(Int32));
					
					if ( objCustomCount != null )
					{
						count = (int) objCustomCount;
					}
				}
			}
			
			return results;
		}
		
		/// <summary>
		/// Gets the values of any supplied parameters for internal caching.
		/// </summary>
		/// <param name="values">An IDictionary object of name/value pairs.</param>
		protected override void GetSelectParameters(IDictionary values)
		{
			if ( SelectMethod == NewsItemSelectMethod.Get || SelectMethod == NewsItemSelectMethod.GetByItemId )
			{
				EntityId = GetEntityKey(values);
			}
		}

		/// <summary>
		/// Performs a DeepLoad operation for the current entity if it has
		/// not already been performed.
		/// </summary>
		internal override void DeepLoad()
		{
			if ( !IsDeepLoaded )
			{
				NewsItem entity = GetCurrentEntity();
				
				if ( entity != null )
				{
					// execute deep load method
					NewsItemProvider.DeepLoad(GetTransactionManager(), GetCurrentEntity(), EnableRecursiveDeepLoad);
					// set loaded flag
					IsDeepLoaded = true;
				}
			}
		}

		/// <summary>
		/// Performs a DeepLoad operation on the specified entity collection.
		/// </summary>
		/// <param name="entityList"></param>
		/// <param name="properties"></param>
		internal override void DeepLoad(TList<NewsItem> entityList, ProviderDataSourceDeepLoadList properties)
		{
			// execute deep load method
			NewsItemProvider.DeepLoad(GetTransactionManager(), entityList, properties.Recursive, properties.Method, properties.GetTypes());
		}

		#endregion Select Methods
	}
	
	#region NewsItemDataSourceDesigner

	/// <summary>
	/// Provides design-time support in a design host for the NewsItemDataSource class.
	/// </summary>
	public class NewsItemDataSourceDesigner : ProviderDataSourceDesigner<NewsItem, NewsItemKey>
	{
		/// <summary>
		/// Initializes a new instance of the NewsItemDataSourceDesigner class.
		/// </summary>
		public NewsItemDataSourceDesigner()
		{
		}

		/// <summary>
		/// Gets or sets the SelectMethod property.
		/// </summary>
		public NewsItemSelectMethod SelectMethod
		{
			get { return ((NewsItemDataSource) DataSource).SelectMethod; }
			set { SetPropertyValue("SelectMethod", value); }
		}

		/// <summary>Gets the designer action list collection for this designer.</summary>
		/// <returns>The <see cref="T:System.ComponentModel.Design.DesignerActionListCollection"/>
		/// associated with this designer.</returns>
		public override DesignerActionListCollection ActionLists
		{
			get
			{
				DesignerActionListCollection actions = new DesignerActionListCollection();
				actions.Add(new NewsItemDataSourceActionList(this));
				actions.AddRange(base.ActionLists);
				return actions;
			}
		}
	}

	#region NewsItemDataSourceActionList

	/// <summary>
	/// Supports the NewsItemDataSourceDesigner class.
	/// </summary>
	internal class NewsItemDataSourceActionList : DesignerActionList
	{
		private NewsItemDataSourceDesigner _designer;

		/// <summary>
		/// Initializes a new instance of the NewsItemDataSourceActionList class.
		/// </summary>
		/// <param name="designer"></param>
		public NewsItemDataSourceActionList(NewsItemDataSourceDesigner designer) : base(designer.Component)
		{
			_designer = designer;
		}

		/// <summary>
		/// Gets or sets the SelectMethod property.
		/// </summary>
		public NewsItemSelectMethod SelectMethod
		{
			get { return _designer.SelectMethod; }
			set { _designer.SelectMethod = value; }
		}

		/// <summary>
		/// Returns the collection of <see cref="T:System.ComponentModel.Design.DesignerActionItem"/>
		/// objects contained in the list.
		/// </summary>
		/// <returns>A <see cref="T:System.ComponentModel.Design.DesignerActionItem"/>
		/// array that contains the items in this list.</returns>
		public override DesignerActionItemCollection GetSortedActionItems()
		{
			DesignerActionItemCollection items = new DesignerActionItemCollection();
			items.Add(new DesignerActionPropertyItem("SelectMethod", "Select Method", "Methods"));
			return items;
		}
	}

	#endregion NewsItemDataSourceActionList
	
	#endregion NewsItemDataSourceDesigner
	
	#region NewsItemSelectMethod
	
	/// <summary>
	/// Enumeration of method names available for the NewsItemDataSource.SelectMethod property.
	/// </summary>
	public enum NewsItemSelectMethod
	{
		/// <summary>
		/// Represents the Get method.
		/// </summary>
		Get,
		/// <summary>
		/// Represents the GetAll method.
		/// </summary>
		GetAll,
		/// <summary>
		/// Represents the GetPaged method.
		/// </summary>
		GetPaged,
		/// <summary>
		/// Represents the Find method.
		/// </summary>
		Find,
		/// <summary>
		/// Represents the GetByItemId method.
		/// </summary>
		GetByItemId
	}
	
	#endregion NewsItemSelectMethod

	#region NewsItemFilter
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlFilter&lt;EntityColumn&gt;"/> class
	/// that is used exclusively with a <see cref="NewsItem"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class NewsItemFilter : SqlFilter<NewsItemColumn>
	{
	}
	
	#endregion NewsItemFilter

	#region NewsItemExpressionBuilder
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="SqlExpressionBuilder&lt;EntityColumn&gt;"/> class
	/// that is used exclusively with a <see cref="NewsItem"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class NewsItemExpressionBuilder : SqlExpressionBuilder<NewsItemColumn>
	{
	}
	
	#endregion NewsItemExpressionBuilder	

	#region NewsItemProperty
	
	/// <summary>
	/// A strongly-typed instance of the <see cref="ChildEntityProperty&lt;NewsItemChildEntityTypes&gt;"/> class
	/// that is used exclusively with a <see cref="NewsItem"/> object.
	/// </summary>
	[CLSCompliant(true)]
	public class NewsItemProperty : ChildEntityProperty<NewsItemChildEntityTypes>
	{
	}
	
	#endregion NewsItemProperty
}

